﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace QuanLyHocBongSinhVien
{
   public class dbConnection
   {
       public static string ConnectString = "server=(local);database=QLHocBongSV;integrated security = true;";
       SqlConnection conn;
       SqlCommand cmd;
       SqlDataAdapter adapter;

       public dbConnection()
       {
           conn = new SqlConnection(ConnectString);
           cmd = new SqlCommand();
           cmd.Connection = conn;
           adapter = new SqlDataAdapter(cmd);
       }

       public void Check()
       {
           conn.Open();
           conn.Close();
       }

       public DataTable ExecuteQuery(string query, params SqlParameter[] sqlParams)
       {
           DataTable table = new DataTable();
           if (query.Contains(" "))
               cmd.CommandType = CommandType.Text;
           else
               cmd.CommandType = CommandType.StoredProcedure;
           cmd.CommandText = query;
           cmd.Parameters.Clear();
           if (sqlParams.Length > 0)
               cmd.Parameters.AddRange(sqlParams);
           adapter.Fill(table);
           return table;
       }

       public void ExecuteNonQuery(string query, params SqlParameter[] sqlParams)
       {
           try
           {
               // Kiem tra xem ma trung hay khong

               //Kiểm tra xem là câu lệnh hay là Proc
               if (query.Contains(" "))
                   cmd.CommandType = CommandType.Text;
               else
                   cmd.CommandType = CommandType.StoredProcedure;

               cmd.CommandText = query;

               cmd.Parameters.Clear();
               if (sqlParams.Length > 0) cmd.Parameters.AddRange(sqlParams);

               conn.Open();
               cmd.ExecuteNonQuery();
           }
           catch (Exception E)// Cac cong viec can lam khi co loi
           {
               System.Windows.Forms.MessageBox.Show(E.Message);
           }


            finally// Cac cong viec luon can thuc hien du loi hay khong
           {
               conn.Close();
           }
       }
    }
}
